/**
 *
 */
package com.hunantv.mglive.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author QiuDa
 */
public class PackageUtil {
    private static final String TAG = "PackageUtil";

    /**
     * @return 获得手机deviceId
     */
    public static String getDeviceId(Context content) {

        String androidId = null;
        androidId = ((TelephonyManager) content.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        if (androidId == null || "".equals(androidId)) {
            androidId = Secure.getString(content.getContentResolver(), Secure.ANDROID_ID);
        }
        return androidId;
    }

    /**
     * 指定的activity所属的应用，是否是当前手机的顶级
     *
     * @param context activity界面或者application
     * @return 如果是，返回true；否则返回false
     */
    public static boolean isTopApplication(Context context) {
        if (context == null) {
            return false;
        }

        try {
            String packageName = context.getPackageName();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
            if (tasksInfo.size() > 0) {
                // 应用程序位于堆栈的顶层
                if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    public static boolean isTopActivity(Context context, String name) {
        if (context == null || StringUtil.isNullorEmpty(name)) {
            return false;
        }

        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
            if (tasksInfo.size() > 0) {
                // 应用程序位于堆栈的顶层
                if (tasksInfo.get(0).topActivity.getClassName().contains(name)) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    /**
     * 指定的activity所属的应用，是否在运行
     *
     * @param context
     * @return
     */
    public static boolean isApplicationRunning(Context context) {
        if (context == null) {
            return false;
        }

        try {
            String packageName = context.getPackageName();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(10);
            for (int i = 0; i < tasksInfo.size(); i++) {
                if (packageName.equals(tasksInfo.get(i).topActivity.getPackageName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    /**
     * 读取manifest.xml中application标签下的配置项，如果不存在，则返回空字符串
     *
     * @param key 键名
     * @return 返回字符串
     */
    public static String getConfigString(Context context, String key) {
        String val = "";
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            val = appInfo.metaData.getString(key);
            if (val == null) {
                L.e(TAG, "please set config value for " + key + " in manifest.xml first");
            }
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return val;
    }

    public static boolean hasInstalledApp(Context context, String packagename) {
        if (StringUtil.isNullorEmpty(packagename)) {
            return false;
        }
        PackageManager packageMgr = context.getPackageManager();
        List<PackageInfo> list = packageMgr.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            PackageInfo info = list.get(i);
            String temp = info.packageName;
            if (temp.equals(packagename)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 读取manifest.xml中application标签下的配置项，如果不存在，则返回空字符串
     *
     * @param key 键名
     * @return 返回字符串
     */
    public static int getConfigInt(Context context, String key) {
        int val = -1;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            val = appInfo.metaData.getInt(key);
            if (val == -1) {
                L.e(TAG, "please set config value for " + key + " in manifest.xml first");
            }
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return val;
    }

    /**
     *
     */
    public static void startInstallAPK(Context mContext, File file) {
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    public static String getSign(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            String sign = signatureMD5(context, info.signatures);
            sign = sign.toUpperCase();
            L.d(TAG, sign);
            return sign;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return null;
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     * 返回当前程序版本号
     */
    public static int getAppVersionCode(Context context) {
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
           return pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return 0;
    }

    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F'};

    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    public static String signatureMD5(Context context, Signature[] signatures) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            if (signatures != null) {
                for (Signature s : signatures)
                    digest.update(s.toByteArray());
            }
            return toHexString(digest.digest());
        } catch (Exception e) {
            L.e(TAG, e);
            return "";
        }
    }

    private static String getChanelStrFromFile(Context context, String file) {
        String fromStr = "META-INF/ynf_";
        Enumeration<?> entries = null;
        ZipFile zipfile = null;
        String id = "";
        try {
            zipfile = new ZipFile(file);
            entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.getName().startsWith(fromStr)) {
                    L.d(TAG, "渠道号为:  " + entry.getName());
                    id = entry.getName().substring(fromStr.length());
                    break;
                }
            }
            zipfile.close();
        } catch (IOException e) {
            L.e(TAG, e);
        }
        return id;
    }

    /**
     * @param context 上下文
     * @param key     权限关键字
     * @return 是否有权限
     */
    public static boolean checkPermission(Context context, String key) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.checkPermission(key, context.getPackageName()) == 0;
    }
}
